import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import { authAPI } from '@/api/auth'

const routes = [
    {
        path: '/',
        redirect: to => {
            // 根据用户角色重定向
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            return userInfo.role === 'ADMIN' ? '/dashboard' : '/profile'
        }
    },
    // 登录页面 - 不需要布局
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: { title: '用户登录', requiresAuth: false }
    },
    // 管理员专用页面
    {
        path: '/jobs',
        component: Layout,
        meta: { requiresAuth: true, requiresRole: 'ADMIN' },
        children: [
            {
                path: '',
                name: 'JobList',
                component: () => import('@/views/jobs/JobList.vue'),
                meta: { title: '任务列表', requiresRole: 'ADMIN' }
            },
            {
                path: 'create',
                name: 'JobCreate',
                component: () => import('@/views/jobs/JobForm.vue'),
                meta: { title: '创建任务', requiresRole: 'ADMIN' }
            },
            {
                path: 'edit/:id',
                name: 'JobEdit',
                component: () => import('@/views/jobs/JobForm.vue'),
                meta: { title: '编辑任务', requiresRole: 'ADMIN' },
                props: true
            }
        ]
    },
    {
        path: '/dashboard',
        component: Layout,
        meta: { requiresAuth: true, requiresRole: 'ADMIN' },
        children: [
            {
                path: '',
                name: 'Dashboard',
                component: () => import('@/views/Dashboard.vue'),
                meta: { title: '仪表盘', requiresRole: 'ADMIN' }
            }
        ]
    },
    {
        path: '/files',
        component: Layout,
        meta: { requiresAuth: true, requiresRole: 'ADMIN' },
        children: [
            {
                path: '',
                name: 'FileManager',
                component: () => import('@/views/files/FileManager.vue'),
                meta: { title: 'Java文件管理', requiresRole: 'ADMIN' }
            }
        ]
    },
    {
        path: '/profile',
        component: Layout,
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                name: 'Profile',
                component: () => import('@/views/Profile.vue'),
                meta: { title: '个人中心' }
            }
        ]
    },
    // 404页面
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        redirect: '/jobs'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 检查路由是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)
    
    // 如果不需要认证，直接通过
    if (!requiresAuth) {
        next()
        return
    }
    
    // 检查本地是否有token
    const token = localStorage.getItem('satoken')
    if (!token) {
        // 没有token，跳转到登录页
        next('/login')
        return
    }
    
    try {
        // 验证token是否有效
        const response = await authAPI.checkLogin()
        if (response.data.isLogin) {
            // token有效，检查角色权限
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            const userRole = userInfo.role
            
            // 检查是否需要特定角色
            const requiresRole = to.matched.some(record => record.meta.requiresRole)
            if (requiresRole) {
                const requiredRole = to.matched.find(record => record.meta.requiresRole)?.meta.requiresRole
                
                if (requiredRole && userRole !== requiredRole) {
                    // 权限不足，跳转到个人中心
                    if (to.path !== '/profile') {
                        next('/profile')
                    } else {
                        next()
                    }
                    return
                }
            }
            
            // 权限检查通过，允许访问
            next()
        } else {
            // token无效，清除本地存储并跳转到登录页
            localStorage.removeItem('satoken')
            localStorage.removeItem('userInfo')
            next('/login')
        }
    } catch (error) {
        // 验证失败，清除本地存储并跳转到登录页
        console.error('Token验证失败:', error)
        localStorage.removeItem('satoken')
        localStorage.removeItem('userInfo')
        next('/login')
    }
})

export default router